#!/usr/bin/env python3

import cgi,os
import tempfile

def app(env, start_response):
    message = ''
    status = '200 OK'
    try:
        tmp_file = tempfile.TemporaryFile()
        for data in env['wsgi.input']:
            tmp_file.write(data)
        tmp_file.seek(0)
        form = cgi.FieldStorage(fp=tmp_file,environ=env,keep_blank_values=True)
        # Get filename here.
        fileitem = form['uploadfile']
        fn = '/home/fuhz/MyShare/upload/' + os.path.basename(fileitem.filename)
        fp = open(fn.encode('utf8'), 'wb')
        for chunk in fileitem.file:
            fp.write(chunk)
        fp.close()
        #status = '500 InternalServerError'
        message = '上传成功： ' + os.path.basename(fileitem.filename)
    except Exception as e:
        #message = '上传失败'
        status = '500 InternalServerError'
        message='上传失败：'+str(e)
    tmp_file.close()
    body = """<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>上传结果</title>
</head>
<body>
   <p>"""+message+"""</p>
</body>
</html>
"""
    body=body.encode('utf-8')
    response_headers = [('Content-Type', 'text/html'),  ('charset','UTF-8'),('Content-Length', str(len(body)))] 
    #status = '200 OK'
    start_response(status, response_headers) 
    return [body]

